import axios from 'axios';
import {Toast} from "vant";
import {codeMsg} from "@/config/codeMsg";
import {keInList} from "@/utils/comFn";
import router from "@/config/router";

/**
 * 设置头部信息
 * @param type 请求头类别 0：为普通请求，1为文件上传
 */
function setHeader(type = 0) {
    // 数据请求格式
    const contentTypes = ['application/json;charset=utf-8', 'multipart/form-data'];
    // 请求头
    const headers = {
        'Content-Type': contentTypes[type]
    };
    return axios.create({
        withCredentials: false,
        headers: headers
    })
}

/**
 * 数据消息处理
 * @param res 服务返回信息
 * @param success 数据成功回调
 * @param fail 数据失败回调
 * @returns
 */
function httpInfo({code, msg, data}: any, success: any, fail: any) {
    console.log(code);
    // 成功返回数据
    if (keInList(code, [200, '200'])) {
        success && success(data);
        return;
    }
    // 失败返回数据
    fail && fail(null);
    // 错误信息提醒

    Toast(codeMsg[code] || msg || '服务器异常');
    //没有权限
    keInList(code, [401, 302,]) && router.replace({path: '/login'});
}

/**
 * 发送http数请请求
 */
function sendHttp(type = 0, method: any, url = '', data: any, success: any, fail: any) {
    return setHeader(type)({
        method,
        url,
        timeout: 40000,
        data: keInList(method, ['POST', "PUT"]) ? data : null,
        params: keInList(method, ['DELETE', "GET"]) ? data : null,
    }).then((res: any) => httpInfo(res.data, success, fail)).catch((res) => httpInfo({
        code: res['status'] || 500,
        msg: '服务异常',
        data: null
    }, success, fail));
}

export default {
    get: (url: string, data: any, success: any=null, fail: any=null) => sendHttp(0, 'GET', url, data, success, fail),
    post: (url: string, data: any, success: any=null, fail: any=null) => sendHttp(0, 'POST', url, data, success, fail),
    put: (url: string, data: any, success: any=null, fail: any=null) => sendHttp(0, 'PUT', url, data, success, fail),
    delete: (url: string, data: any, success: any=null, fail: any=null) => sendHttp(0, 'DELETE', url, data, success, fail),
    file: (url: string, data: any, success: any=null, fail: any=null) => sendHttp(1, 'POST', url, data, success, fail),
    promise: (method: string, url: string, data: any) => (new Promise((resolve, reject) => sendHttp(0, method, url, data, resolve, reject))),
}